package com.add;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Semaphore 信号量，用来限流
 * 作用：多个共享资源互斥的使用
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        //3个信号量
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                try {
                    //acquire() 从该信号量获取许可证；假如信号量已经满了，则会等待，直到被释放位置
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "抢到车位（信号量）");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "离开车位（信号量）-----------");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //release()  释放许可证，将其返回信号量；然后唤醒等待的线程
                    semaphore.release();
                }


            }, String.valueOf(i)).start();

        }

    }
}
